public class Solution130 {
    public void solve(char[][] board) {
        int m = board.length;
        int n = board[0].length;
        boolean[][] change = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O') {
                dfs(board, change, i, 0);
            }
            if (board[i][n - 1] == 'O') {
                dfs(board, change, i, n - 1);
            }
        }
        for (int i = 0; i < n; i++) {
            if (board[0][i] == 'O') {
                dfs(board, change, 0, i);
            }
            if (board[m - 1][i] == 'O') {
                dfs(board, change, m - 1, i);
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O' && !change[i][j]) {
                    board[i][j] = 'X';
                }
            }
        }
    }

    void dfs(char[][] board, boolean[][] change, int i, int j) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return;
        }
        if (change[i][j]) {
            return;
        }
        if (board[i][j] == 'X') {
            return;
        }
        change[i][j] = true;
        dfs(board, change, i + 1, j);
        dfs(board, change, i - 1, j);
        dfs(board, change, i, j + 1);
        dfs(board, change, i, j - 1);
    }
}
